package cn.git.shiro.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @description: shiro测试类
 *         // 1.获取SecurityManager对象
 *         // 2.获取Subject对象
 *         // 3.获取页面传入参数，此处模拟
 *         // 4.调用Subject对象的方法login()
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-26
 */
public class ShiroMain {
    public static void main(String[] args) {
        // 1.获取SecurityManager对象
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        // 2.获取Subject对象
        Subject subject = SecurityUtils.getSubject();

        // 3.获取页面传入参数，此处模拟
        AuthenticationToken token = new UsernamePasswordToken("zhangsan", "123456");

        // 4.调用Subject对象的方法login()
        try {
            subject.login(token);
            System.out.println("认证成功");
            // 角色判定
            if (subject.hasRole("admin")) {
                System.out.println("拥有admin角色");
            } else if (subject.hasRole("guest")) {
                System.out.println("拥有guest角色");
            }

            // 判定当前用户所有权限
            if (subject.isPermitted("user:insert")) {
                System.out.println("拥有user:insert权限");
            }
            if (subject.isPermitted("user:delete")) {
                System.out.println("拥有user:delete权限");
            }
            if (subject.isPermitted("user:update")) {
                System.out.println("拥有user:update权限");
            }
            if (subject.isPermitted("user:select")) {
                System.out.println("拥有user:select权限");
            }
            // checkPermission方法会抛出异常
            subject.checkPermission("user:select");

        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        } catch (AuthenticationException e) {
            System.out.println("认证失败");
        }
    }
}
